package Algorithm.others;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Desc:   两个线程交替打印奇偶数
 * @author: cww
 * @DateTime: 2020/6/9 12:12
 */

public class PrintOddEven {
    private int start = 1;
    private volatile boolean flag = false;
    public static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        PrintOddEven oddEven = new PrintOddEven();
        Thread t1 = new Thread(new OddThread(oddEven));
        t1.setName("T1");
        Thread t2 = new Thread(new EvenThread(oddEven));
        t2.setName("T2");
        t1.start();
        t2.start();
    }

    public boolean isFlag() {
        return flag;
    }

    public int getStart() {
        return start;
    }

    public void setStart() {
        this.start++;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

class OddThread implements Runnable{

    private PrintOddEven num;

    public OddThread(PrintOddEven num) {
        this.num = num;
    }

    /**
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (num.getStart()<=1000){
            if (num.isFlag()){
                try {
                    PrintOddEven.lock.lock();
                    System.out.println(Thread.currentThread().getName() + " " + num.getStart());
                    num.setStart();
                    num.setFlag(false);
                } finally {
                    PrintOddEven.lock.unlock();
                }

            }
        }
    }
}

class EvenThread implements Runnable {
    private PrintOddEven num;

    public EvenThread(PrintOddEven num) {
        this.num = num;
    }

    /**
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (num.getStart()<=1000){
            if(!num.isFlag()){
                try {
                    PrintOddEven.lock.lock();
                    System.out.println(Thread.currentThread().getName() + " " + num.getStart());
                    num.setStart();
                    num.setFlag(true);
                } finally {
                    PrintOddEven.lock.unlock();
                }
            }
        }

    }
}
